import React, { Component } from 'react'
import qs from 'qs'
import store from 'store'
import _ from 'lodash'
import axios from 'axios'
import { url, api } from 'config/api'
import moment from 'moment'
import { connect } from 'react-redux'
import cs from 'classnames'

import {
  Alert,
  Button,
  Form
} from 'antd'

import {
  List,
  Toast,
  InputItem, Modal as AntdModal,
} from 'antd-mobile'

import Layout from 'component/layout'
import HeaderLayout from 'layout/header'

import { getPreselect, getLockHouse, inputUserInfo, login } from 'model/user'
import { inputBuildingInfo, getBuilding } from 'model/building'
import { getHouse, switchChoiceHouseType } from 'model/house'

import { timeFormat, formatDuring, calcTime } from 'config/time'

import { sendMessageToNative } from 'utils/sendMessageToNative'
import countdown from 'utils/countdown'

import style from './index.less'
import { NoticeBar } from 'antd-mobile'

const { alert } = AntdModal

const {
  Content,
  Footer,
} = Layout

@connect(state => ({
  user: state.user,
  building: state.building,
}), {
  inputUserInfo,
  inputBuildingInfo,
  getPreselect,
  getLockHouse,
  getBuilding,
  getHouse,
  switchChoiceHouseType,
  login
})
export default class App extends Component {
  isMount = true

  constructor (props) {
    super(props)

    const query = qs.parse(props.location.search.replace(/^\?/g, ''))

    const {
      // 楼盘id
      propertyId    = props.building.propertyId,
      // 开盘期id
      housePreiodId = props.building.housePreiodId,
      // 楼盘名称
      propertyName  = props.building.propertyName,
      // 开盘名称
      housePreiodName  = props.building.housePreiodName,
    } = query
    let msg = ''

    if (!propertyId) {
      msg = '缺少参数[propertyId]'
    } else if (!housePreiodId) {
      msg = '缺少参数[housePreiodId]'
    } else if (!propertyName) {
      msg = '缺少参数[propertyName]'
    } else if (!housePreiodName) {
      msg = '缺少参数[housePreiodName]'
    }

    props.inputBuildingInfo({
      propertyId,
      housePreiodId,
    })

    this.state = {
      msg,

      propertyId,
      housePreiodId,
      propertyName,
      housePreiodName,

      vCodeIndex: 60,
      isWaitVCode: false,
      // 是否获取成功了验证码
      isGetVCode: false,
      phoneError: false,
      vCodeError: false,
      phone: '',
      vCode: ''
    }

    this.timer = null
  }

  componentDidMount () {
    if (!this.state.msg) {
      this.timer = setInterval(() => this.forceUpdate(), 1000)
    }
  }

  componentWillUnmount () {
    clearTimeout(this.timer)
    this.timer = null

    this.isMount = false
  }

  initData = () => {
    const {
      phone,
      propertyId,
      housePreiodId,
    } = this.state

    this.props.getBuilding({
      phone,
      propertyId,
      housePreiodId,
    })

    this.props.getHouse({
      phone,
      propertyId,
      housePreiodId,
    })

    this.props.getPreselect({
      phone,
      propertyId,
      housePreiodId,
    })

    this.props.getLockHouse({
      phone,
      propertyId,
      housePreiodId,
    })
  }

  handleSubmit = async () => {
    const {
      phone,
      propertyId,
      housePreiodId,
      vCode: mscode
    } = this.state

    if (!(phone && mscode)) {
      alert('提示', '请填写完整信息', [
        { text: '知道了' },
      ])
      return
    }

    Toast.loading('登录中', 0, null, true)

    this.props.login({
      phone,
      propertyId,
      housePreiodId,
      mscode
    })

    Toast.hide()

    // if (err) {
    //   alert('提示', err, [
    //     { text: '知道了' },
    //   ])

    //   return
    // }

    this.initData()
    this.props.inputUserInfo({ phone })
    Toast.success('登录成功', 2, () => {
      this.props.history.push('/home')
    }, false)
  }

  // 获取验证码
  handleVCode = async () => {
    if (this.state.isWaitVCode) {
      return
    }

    const { phone, propertyId, housePreiodId } = this.state

    if (!phone || !/^1\d{10}$/.test(phone)) {
      alert('提示', '手机号格式有误', [
        { text: '知道了' },
      ])
      this.setState({ phoneError: true })

      return
    }

    Toast.loading('发送验证码中', 0, null, true)

    const [err, res] = await axios.post(url.server + api.sendVCode, { phone, propertyId, housePreiodId })

    Toast.hide()

    if (err) {
      alert('提示', err, [
        { text: '知道了' },
      ])

      return
    }

    this.setState({
      isWaitVCode: true,
      isGetVCode: true
    })

    Toast.success('验证码发送成功', 2, null, false)

    countdown(60, v => {
      if (!this.isMount) {
        return
      }

      this.setState({ vCodeIndex: v + ' s' })
    }, () => {
      if (!this.isMount) {
        return
      }

      this.setState({ isWaitVCode: false })
    })
  }

  changePhone = (v) => {
    const phone = v.replace(/\s/g, '')

    if ( phone && !/^1\d{10}$/.test(phone)) {
      this.setState({ phoneError: true })
    } else {
      this.setState({ phoneError: false })
    }

    this.setState({ phone })
  }

  changeVCode = (v) => {
    const vCode = v.replace(/\s/g, '')

    if (vCode && !/^[0-9]*$/.test(v)) {
      this.setState({ vCodeError: true })
    } else {
      this.setState({ vCodeError: false })
    }

    this.setState({ vCode })
  }

  render () {
    const {
      msg,
      phone,
      phoneError,
      vCode,
      vCodeError,
      vCodeIndex,
      isWaitVCode,
      isGetVCode,

      propertyName,
      housePreiodName,
    } = this.state

    return (
      <Layout fixed >
        <div className = { style['page'] } >
          <div className = { style['page-bg'] } >
            {
              msg ?
                <div className = { style['alert'] }>
                  <Alert
                    message = { msg }
                    type = 'error'
                    showIcon
                  />
                </div> :
                null
            }
            <p className = { style['title'] } >{ propertyName } { housePreiodName }</p >
          </div>
          <Form onSubmit = { this.handleSubmit } className = { style['login-form'] } >
            <List>
              <InputItem
                type = 'phone'
                clear
                placeholder = '请输入手机号'
                error = { phoneError }
                value = { phone }
                onChange = { this.changePhone }
              >
                <div className = { style['login-form-pho'] }></div>
              </InputItem>
              <InputItem
                type = 'number'
                error = { vCodeError }
                placeholder = '验证码'
                onChange = { this.changeVCode }
                extra = {
                  !isWaitVCode ?
                    '获取验证码' :
                    vCodeIndex
                }
                value = { vCode }
                onExtraClick = { this.handleVCode }
              >
                <div className = { style['login-form-ver'] }></div>
              </InputItem>
            </List>
            <div className = { style['login-button'] }>
              <Button disabled = { !vCode || !phone || !isGetVCode } onClick = { this.handleSubmit } type = 'primary' block >登录</Button>
            </div>
          </Form>
          <p className = { style['page-footer'] }>在线选房系统由 <span>壹房通</span> 提供</p>
        </div>
      </Layout>
    )
  }
}
